package main

import (
	"context"
	"fmt"
	core_v1 "k8s.io/api/core/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

// 使用serviceaccount的crt和token来验证
func main() {
	var (
		clientset *kubernetes.Clientset
		podsList  *core_v1.PodList
		err       error
	)
	// token和crt都是从挂载的文件里获取(token、ca.crt)
	host := "https://127.0.0.1:38581"
	token := "eyJhbGciOiJSUzI1NiIsImtpZCI6Ik9rRFlWbVlBc2NGVGt3azBId0NVNDhac2VJaHlHN3RUTWFvU1dobU51T3cifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tbGs3cHQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjhjY2Q2ODk3LTI3MTUtNDU5NC1iOGI4LTE2YzlhNGMwYWQ1NyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.ya8aYhO9mz08T0_knkX405LMw5JMXecBGvydCYbyT9TMS4Ito4pNfVUtIQSuiUzwmzZ5_FuLAMfdiDvCmczykvoWwqmwwmfBac-qo79mW_k39H3tW3FaL1AsmRmEQ7rVp2jW7CeEY_--9Y9JSUU5cucHlDTX7fUnJx6WdtOpxdd831rxY-c_JXdWBE99SISLWKe0YNG9aOhz3hDfJLT7KsSnnqQBCDlEszBtGlEkIJqCzc4KMDJVcg_3A-lt4f2mikabQlW4vj0qpVLgMUEym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g7qXQ7jw4MIjFc57FmGzVTr2UzfkZ2IuX
-----END CERTIFICATE-----
`
	// 初始化k8s客户端
	tlsClientConfig := rest.TLSClientConfig{
		CAData: []byte(caData),
	}
	restConf := rest.Config{
		Host:            host,
		BearerToken:     token,
		TLSClientConfig: tlsClientConfig,
	}
	// 生成clientset配置
	if clientset, err = kubernetes.NewForConfig(&restConf); err != nil {
		goto FAIL
	}
	// 获取default命名空间下的所有POD
	if podsList, err = clientset.CoreV1().Pods("default").List(context.TODO(), meta_v1.ListOptions{}); err != nil {
		goto FAIL
	}
	fmt.Println(*podsList)

	return

FAIL:
	fmt.Println(err)
	return
}

// 如果token为空，则报错：
// pods is forbidden: User "system:anonymous" cannot list resource "pods" in API group "" in the namespace "default"
// 如果serviceaccount没有绑定权限，也会报错：
// pods is forbidden: User "system:serviceaccount:default:default" cannot list resource "pods" in API group "" in the namespace "default"
